package main.java;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.function.Function;

public class GenericConverter {
    // 个性化要求：添加学号常量（绑定学号202411671214）
    public static final String STUDENT_ID = "202411671214";

    // 映射转换：将source容器的元素通过mapper转换为R类型，返回新容器
    public static <T, R> DataContainer<R> convert(DataContainer<T> source, Function<T, R> mapper) {
        if (source == null || mapper == null) {
            throw new IllegalArgumentException("source and mapper cannot be null");
        }
        DataContainer<R> result = new DataContainer<>();
        for (int i = 0; i < source.size(); i++) {
            T element = source.get(i);
            R converted = mapper.apply(element);
            result.add(converted);
        }
        return result;
    }

    // 反转容器元素顺序：返回新容器，原容器不变
    public static <T> DataContainer<T> reverse(DataContainer<T> source) {
        if (source == null) {
            throw new IllegalArgumentException("source cannot be null");
        }
        // 先获取source的副本列表，避免修改原容器
        List<T> sourceList = source.toList();
        Collections.reverse(sourceList); // 反转列表
        return new DataContainer<>(sourceList); // 基于反转后的列表创建新容器
    }

    // 自然排序：元素需实现Comparable，返回新容器
    public static <T extends Comparable<? super T>> DataContainer<T> sort(DataContainer<T> source) {
        if (source == null) {
            throw new IllegalArgumentException("source cannot be null");
        }
        List<T> sourceList = source.toList();
        // 选择Collections.sort()：底层为TimSort（归并+插入），时间复杂度O(n log n)，稳定性好，JDK原生优化
        Collections.sort(sourceList);
        return new DataContainer<>(sourceList);
    }

    // 自定义排序：通过comparator指定排序规则，返回新容器
    public static <T> DataContainer<T> sort(DataContainer<T> source, Comparator<? super T> comparator) {
        if (source == null || comparator == null) {
            throw new IllegalArgumentException("source and comparator cannot be null");
        }
        List<T> sourceList = source.toList();
        // 自定义排序：使用传入的comparator，底层同样为TimSort，时间复杂度O(n log n)
        Collections.sort(sourceList, comparator);
        return new DataContainer<>(sourceList);
    }
}